import 'dart:async';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:interview/controller/interview_controller.dart';
import 'package:interview/servers/question_detail.dart';
import 'package:interview/servers/question_opt.dart';
import 'package:interview/utils/logger.dart';

class InterviewDetailsController extends GetxController {
  final InterviewController _controller = Get.find<InterviewController>();
  final RxMap<String , QuestionDetail> interviewDetails = <String , QuestionDetail>{}.obs;
  final GetStorage _storage = GetStorage('interview_details_box');
  static const int maxEntries = 12;

  @override
  void onInit() {
    super.onInit();
    _loadStoredData(); // 加载持久化数据
  }

  /// 加载本地持久化的数据
  void _loadStoredData() {
    try {
      final storedData = _storage.read('interviewDetails') as Map<String, dynamic>?;
      if (storedData != null) {
        // 将持久化的 Map 转换回内存中的数据结构
        interviewDetails.addAll(storedData.map((key, value) => MapEntry(key, QuestionDetail.fromJson(value))));
        Logger.info("加载持久化数据成功", tag: "loadStoredData");
      }else{
        Logger.info("无持久化数据", tag: "loadStoredData");
      }
    } catch (e) {
      Logger.error("加载持久化数据失败 $e", tag: "loadStoredData");
    }
  }
  /// 持久化保存数据到本地
  void _persistData() {
    try {
      final dataToStore = interviewDetails.map((key, value) => MapEntry(key,value.toJson()));
      _storage.write('interviewDetails', dataToStore); // 保存数据
      Logger.info("数据已持久化", tag: "persistData");
    } catch (e) {
      Logger.error("持久化数据失败 $e", tag: "persistData");
    }
  }

  /// 判断数据是否存在
  bool hasQuestionDetail(String id) => interviewDetails.containsKey(id);
  /// 获取指定 id 的 QuestionDetail
  QuestionDetail? getQuestionDetail(String id) => interviewDetails[id];

  bool checkDetail(int newViews , String id){
    var detail = getQuestionDetail(id);
    if (detail != null) {
      // 同步 views，如果有新值，更新内存和持久化数据
      if (newViews > 0 && detail.views.value != newViews) {
        detail.views.value = newViews;
        _persistData(); 
      }
      return true; 
    }else{
      return false; 
    }
  }

  /// 加载 QuestionDetail 数据
  Future<void> loadQuestionDetail(int newViews , int typeId, String id, Future<QuestionDetail> Function() fetchDetail) async {
    // 检查数据是否已存在
    var detail = getQuestionDetail(id);
    if (detail != null) {
      if(newViews > 0 && detail.views.value != newViews){
        detail.views.value = newViews;
        _persistData();
      }
      return; // 数据已存在，直接返回
    }
    // 数据不存在，调用接口获取数据
    try {
      var detail = await fetchDetail(); // 调用传入的异步方法获取数据
      interviewDetails[id] = detail; // 添加数据
      // 数据量控制：限制最多 20 条记录
      if (interviewDetails.length > maxEntries) {
        String oldestKey = interviewDetails.keys.first; // 获取最早加入的 key
        interviewDetails.remove(oldestKey); // 移除最早的数据
        Logger.info("移除持久化数据", tag: "persistData");
      }
      _persistData(); // 持久化数据
      Logger.info("更新 interviewDetails", tag: "loadQuestionDetail");
    } catch (e) {
      Logger.error("加载 QuestionDetail 失败 $e", tag: "loadQuestionDetail");
      rethrow;
    }
  }


  Timer? _debounce; // 防抖用的 Timer
  
  /// 修改点赞数量
  Future<void> toggleLikeCount( String tab , String id, String changeType , String type ,) async {
    if(_debounce?.isActive ?? false) return; 
    _debounce = Timer(const Duration(milliseconds: 500),  () async{
      final detail = getQuestionDetail(id);
      if (detail == null) return;
      final preLikeCount = detail.likeCount.value;
      final isAdd = changeType == "add";
      final increment = isAdd ? 1 : -1; 
      try {
        // 乐观更新
        if(type == "like"){
          detail.likeCount.value += increment;
          detail.likeFlag.value = isAdd ? 1 :0;
          _controller.toggleLikeCount(tab, id, detail.likeCount);
          
        }else if (type == "collect"){
          detail.collectFlag.value = isAdd ? 1 :0;
        }
        interviewDetails.refresh();
        _persistData();
        if(type == "like"){
          await questionOptApi(id , detail.likeFlag , type);
        }else if (type == "collect"){
          await questionOptApi(id , detail.collectFlag , type);
        }
      } catch (e) {
        if(type == "like"){
          detail.likeCount.value = preLikeCount;
          detail.likeFlag.value = isAdd ? 0 : 1;
          _controller.toggleLikeCount(tab, id, detail.likeCount);
          Logger.warn("点赞失败 ${detail.likeFlag.value} , 当前 ${detail.likeCount.value}" , tag: "toggleLikeCount");
        }else if (type == "collect"){
          detail.collectFlag.value = isAdd ? 0 : 1;
        }
        interviewDetails.refresh();
        _persistData();
      }
    });
  }

  Future <void> questionOptApi (String id , RxInt likeFlag , type) async {
    final params = QuestionOptParams(
      id: id, 
      optType: type == "like" ? 1 : 2 ,  // 点赞是1  收藏是2
      type: 1 // 0是面试题 1是面经
    );
    await fetchQuestionOpt(params , likeFlag.value , null);
  }
}